/*
 *
 *  * -------------------------------------------------------------------------------------
 *  *    Mi-Me Confidential
 *  *
 *  *    Copyright (C) 2015 Shanghai Mi-Me Financial Information Service Co., Ltd.
 *  *    All rights reserved.
 *  *
 *  *    No part of this file may be reproduced or transmitted in any form or by any means,
 *  *    electronic, mechanical, photocopying, recording, or otherwise, without prior
 *  *    written permission of Shanghai Mi-Me Financial Information Service Co., Ltd.
 *  * -------------------------------------------------------------------------------------
 *
 *
 */

package cn.mimedai.blurlib.background;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

public class BlurBehind {

    private static final String KEY_CACHE_BLURRED_BACKGROUND_IMAGE =
            "KEY_CACHE_BLURRED_BACKGROUND_IMAGE";
    private static final int CONSTANT_BLUR_RADIUS = 12;
    private static final int CONSTANT_DEFAULT_ALPHA = 100;

    private static final int CONSTANT_BLUR_RADIUS_MAX = 25;
    private static final int CONSTANT_BLUR_RADIUS_MIN= 1;

    private static final LruCache<String, Bitmap> mImageCache = new LruCache<String, Bitmap>(1);
    private static CacheBlurBehindAndExecuteTask cacheBlurBehindAndExecuteTask;

    private int mAlpha = CONSTANT_DEFAULT_ALPHA;
    private int mFilterColor = -1;

    private enum State {
        READY,
        EXECUTING
    }

    private State mState = State.READY;

    private static BlurBehind mInstance;

    public static BlurBehind getInstance() {
        if (mInstance == null) {
            mInstance = new BlurBehind();
        }
        return mInstance;
    }

    public void execute(Activity activity, OnBlurCompleteListener onBlurCompleteListener) {
        execute(activity, onBlurCompleteListener, CONSTANT_BLUR_RADIUS);
    }

    public void execute(Activity activity, OnBlurCompleteListener onBlurCompleteListener, int radius) {
        if (mState.equals(State.READY)) {
            mState = State.EXECUTING;
            if (radius > CONSTANT_BLUR_RADIUS_MAX || radius < CONSTANT_BLUR_RADIUS_MIN) {
                throw new IllegalArgumentException("The radius must in between of 1 and 25!");
            }
            cacheBlurBehindAndExecuteTask = new CacheBlurBehindAndExecuteTask(activity,
                    onBlurCompleteListener, radius);
            cacheBlurBehindAndExecuteTask.execute();
        }
    }

    public BlurBehind withAlpha(int alpha) {
        this.mAlpha = alpha;
        return this;
    }

    public BlurBehind withFilterColor(int filterColor) {
        this.mFilterColor = filterColor;
        return this;
    }

    public void setBackground(Activity activity) {
        if (mImageCache.size() != 0) {
            BitmapDrawable bd = new BitmapDrawable(activity.getResources(),
                    mImageCache.get(KEY_CACHE_BLURRED_BACKGROUND_IMAGE));
            //通过设置Fragment的背景颜色精确控制效果
//            if (mFilterColor != -1) {
//                bd.setColorFilter(mFilterColor, PorterDuff.Mode.DST_ATOP);
//            }
//            bd.setAlpha(mAlpha);
            activity.getWindow().setBackgroundDrawable(bd);
            mImageCache.remove(KEY_CACHE_BLURRED_BACKGROUND_IMAGE);
            cacheBlurBehindAndExecuteTask = null;
        }
    }

    private class CacheBlurBehindAndExecuteTask extends AsyncTask<Void, Void, Void> {
        private Activity activity;
        private OnBlurCompleteListener onBlurCompleteListener;

        private View decorView;
        private Bitmap image;
        private int mRadius;

        public CacheBlurBehindAndExecuteTask(Activity activity,
                OnBlurCompleteListener onBlurCompleteListener, int radius) {
            this.mRadius = radius;
            this.activity = activity;
            this.onBlurCompleteListener = onBlurCompleteListener;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            decorView = activity.getWindow().getDecorView();
            int width = decorView.getWidth() <= 0 ? getScreenWidth(activity) : decorView.getWidth();
            int height = decorView.getHeight() <= 0 ? getScreenHeight(activity) : decorView.getHeight();
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
            decorView.draw(new Canvas(bitmap));
            image = bitmap;
        }

        @Override
        protected Void doInBackground(Void... params) {
            //image 解析不出来的异常情况处理 保证image不为空
            if (image != null) {
                Bitmap blurredBitmap = Blur.apply(activity, image, mRadius);
                mImageCache.put(KEY_CACHE_BLURRED_BACKGROUND_IMAGE, blurredBitmap);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            activity = null;
            if (onBlurCompleteListener != null) {
                onBlurCompleteListener.onBlurComplete();
            }

            mState = State.READY;
        }
    }

    private int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    private int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }
}
